<?php
/* MyMeeting is an online meeting management software.
 * Copyright (C) 2009 Government Of Malaysia
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * @author: Abdullah Zainul Abidin, Nuhaa All Bakry
 *          Eavay Javay Barnad, Sarogini Muniyandi, Teow Jit Huan
 *
 */

class MembershipsController extends AppController {

    /**
     * Define $name
     *
     */
    var $name = 'Memberships';
    /**
     * Define $helpers
     *
     */
    var $helpers = array('Html', 'Form', 'Crumb','Javascript','Ajax');
    /**
     * To set a default sort order
     */
    var $paginate = array('order'=>array('User.username'=>'ASC'));
    
    var $controller = array('Autocomplete');
    
    var $use =array('User');

    //adding user roles on committee
    /**
     * Describe addroles
     *
     * @return null
     */
    function addroles(){}

    //edditing user roles on committee

    /**
     * Describe editroles
     *
     * @param $id
     * @return null
     */
    function editroles($id = null){
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid Membership', true));
            $this->redirect(array('controller'=>'Committees','action'=>'index'));
        }
        if (!empty($this->data)) {
            if ($this->Membership->save($this->data)) {
                $this->Session->setFlash(__('The changes on user role has been saved', true));
                $this->redirect(array('controller'=>'Committees','action'=>'index'));
            } else {
                $this->Session->setFlash(__('The Membership could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->set('membership', $this->Membership->read(null, $id));    
            $this->data = $this->Membership->read(null, $id);
        }
        $roles = $this->Membership->Role->find('list');
        $this->set(compact('roles'));    
    }    

    /**
     * Describe index
     *
     * @param $committee
     * @return null
     */
    function index($committee) {
        $this->Membership->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Workflow','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Membership->RunReorder($committee);
        $this->Membership->DistinctOrder($this->dcommittee['Committee']['id']);
        $this->Membership->recursive = 1;
        $this->Membership->User->Group->recursive=-1;

        // get the search terms
        if(!empty($this->data['Search']['name']) && $this->data['Search']['name']!='' ) {
            $cursearch_name = $this->data['Search']['name'];
        }else {
            $cursearch_name = '';
        }
        $this->set('cursearch_name',$cursearch_name);

        // construct queries
        $filters =array();
        $cond_group="Group.committee_id = ".$this->dcommittee['Committee']['id'];
        array_push($filters,"Membership.committee_id = ".$this->dcommittee['Committee']['id']);
        if(isset($cursearch_name) && $cursearch_name!='') {
            array_push($filters,"User.name  like '%".$cursearch_name."%'");
            $cond_group.=" and Group.name like '%".$cursearch_name."%'";
        }
        
        if (!isset($this->params['named']['sort']) ) { $this->paginate['Membership'] = array('order'=> 'order_id ASC'); }
        $groups=$this->Membership->User->Group->find('all',array('conditions'=>$cond_group,'order'=>array('Group.name'=>'ASC')));
        $memberships=$this->paginate('Membership', $filters);
        
        Controller::loadModel('Title');
        $this->Title->unbindModel(array('hasMany'=>array('User')));
        $titles = $this->Title->find('all');
        
        if(!$this->Auth->user('superuser')){
            $this->set('secretariat',$this->Membership->isSecretariat($this->dcommittee['Committee']['id'],$this->Auth->user('id')));
        }
        $this->set('groups', $groups);
        $this->set('memberships', $memberships); 
        $this->set('titles', $titles); 
    }

    /**
     * Describe addressbook
     *
     * @return null
     */
    function addressbook() {
        if($this->Session->check('CurCommittee')){
            //to get current selected committee
            $this->set('memberships',$this->paginate('Membership','Committee.id='.$this->Session->read('CurCommittee')));
        }
        else
        {
            $this->set('memberships',$this->paginate('Membership'));
        }   
    }

    /**
     * Describe view
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function view($committee,$id = null ) {
        
        $this->Membership->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Workflow','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $exist_committee_id=Set::extract($this->Membership->Committee->find('all'),'{n}.Committee.id');
        if (!$id) {
            $this->Session->setFlash(__('Invalid Membership.', true));
            $this->redirect(array('committee'=>$committee,'action'=>'index'));
        }
        $membership = $this->Membership->read(null,$id);
        if(!empty($membership['User']['scheme_id'])){
            $Scheme=$this->Membership->User->Scheme->findById($membership['User']['scheme_id']);
            $membership['User']['scheme']=$Scheme['Scheme']['name'];
        }
        if(!empty($membership['User']['protocol_id'])){
            $Protocol=$this->Membership->User->Protocol->findById($membership['User']['protocol_id']);
            $membership['User']['grade']=$Protocol['Protocol']['protocol_title'];
        }
        $this->set('membership',$membership);
        $this->Membership->User->Title->Behaviors->attach('Containable');
        
        $title1 = $this->Membership->User->find('all',array('conditions'=>array('User.id'=>$membership['User']['id']),'contain'=>'Title'));
        $this->set('title',$title1);
        $this->pageTitle='Memberships';
        $this->Membership->Behaviors->detach('Containable');
        $roles = $this->Membership->find('all',array('conditions'=>array('user_id'=>$membership['User']['id'],'Membership.committee_id'=>$exist_committee_id),'order'=>'Committee.name ASC'));
        $this->set('roles',$roles);
        
    }

    /**
     * Describe add
     *
     * @param $committee
     * @return null
     */
    function add($committee) {
        $this->Membership->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Workflow','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        if (!empty($this->data)) {
            if(!empty($this->data['User']['email'])){
            $duser=$this->Membership->User->field('id',array('email'=>$this->data['User']['email']));
        }
        elseif (!empty($this->data['User']['username'])){
            $duser=$this->Membership->User->field('id',array('username'=>$this->data['User']['username']));
            }
            if(!empty($duser)){  //before fix the code is - if($duser)
                /* The user already exists so grab his id */
                $this->data['Membership']['user_id']=$duser;
            }
        
            else{
                /* If it is actually a new user then save the new user data first and grab the id */
                $this->data['User']['password']=$this->Auth->password($this->data['User']['username']);
                $this->data['User']['password_confirm']=$this->data['User']['username'];
                $this->Membership->User->create();
                if($this->Membership->User->save($this->data['User'])){
                    $this->data['Membership']['user_id']=$this->Membership->User->getLastInsertID();
                }
                else{
                    $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
                    $usersaved=false;
                }
            }
            $this->Membership->create();
            if(isset($this->data['Membership']['user_id']) && $this->Membership->isUnique(array('user_id'=>$this->data['Membership']['user_id'],'committee_id'=>$this->data['Membership']['committee_id']),false)){
                /* Check that the user actually haven't registered with that committee */
                $this->data['Membership']['order_id'] = 1;
                if ($this->Membership->save($this->data)) {
                    $this->Session->setFlash(__('The User has been saved', true));
                    $last_id = $this->Membership->getLastInsertId();
                    if($this->Membership->Committee->find('count',array('conditions'=>array('Committee.id'=>$this->data['Membership']['committee_id'],'Committee.membership_sorted'=>1)))){
                        $total_committee = $this->Membership->find('count',array('conditions'=>array('Membership.committee_id'=>$this->data['Membership']['committee_id'])));
                        $member['Membership']['id']=$last_id;
                        $member['Membership']['order_id']=$total_committee;
                        $this->Membership->save($member);
                    }else{
                        $allmember=$this->Membership->find('all',array('conditions'=>array('Membership.committee_id'=>$this->data['Membership']['committee_id'])));
                        $allmember=$this->Membership->User->Protocol->softByProtocol($allmember);
                        foreach($allmember as $a=>$member){
                            $member['Membership']['order_id']=$a;
                            $this->Membership->save($member);
                        }
                    }
                    $this->redirect(array('controller'=>'Memberships','committee'=>$committee,'action'=>'index'));
                } else {
                    $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
                }
            }
            else{ 
                if(isset($usersaved) && $usersaved){
                    $this->redirect(array('committee'=>$committee,'action'=>'index'));
                }else{
                    $this->Session->setFlash(__('The User already exist in the committee. ', true));
                }
            }
        }
        $users = $this->Membership->User->find('list');
        $roles = $this->Membership->Role->find('list');
        $titles=$this->Membership->User->Title->find('list');
        $schemes=$this->Membership->User->Scheme->find('list');
        $protocols=$this->Membership->User->Protocol->find('list',array('order'=>'Protocol.rank Asc'));
        $this->set(compact('users','roles','titles','protocols','schemes'));
    }
    
    /**
     * Describe edit
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function edit( $committee = null,$id = null) {
        $this->Membership->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Workflow','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->set('dcommittee',$this->dcommittee);
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid Membership', true));
            $this->redirect(array('committee'=>$committee,'action'=>'index'));
        }
        if (!empty($this->data)) {
            if ($this->Membership->save($this->data)) {
                // save user details
                if (!empty($this->data['User'])){
                    $this->User->unbindModel(array('hasMany'=>array('Userstatus','Groupstatus','Announcement','Meetingtodo'),'belongsTo'=>array('Title','Protocol'),'hasAndBelongsToMany'=>array('Committee','Meeting','Decision','Group')),false);
                    if(empty($this->data['User']['name'])){
                        $this->Session->setFlash(__('Name',true).': '.__('This field cannot be left blank',true));
                        $this->redirect(array('committee'=>$committee,'action'=>'edit',$id));
                    }elseif(empty($this->data['User']['email'])){
                        $this->Session->setFlash(__('Email',true).': '.__('This field cannot be left blank',true));
                        $this->redirect(array('committee'=>$committee,'action'=>'edit',$id));
                    }else{
                        $same_email=$this->User->find('first',array('conditions'=>array('User.email'=>$this->data['User']['email'],'User.id !='.$this->data['User']['id'],'User.deleted'=>0)));
                        if(!empty($same_email)){
                            $this->Session->setFlash(__('E-mail already exists',true));
                            $this->redirect(array('committee'=>$committee,'action'=>'edit',$id));
                        }
                    }
                    $this->User->save($this->data);
                }
                $this->Session->setFlash(__('The Membership has been saved', true));
                $this->redirect(array('committee'=>$committee,'action'=>'index'));
            } else {
                $this->Session->setFlash(__('The Membership could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Membership->read(null, $id);
            $this->set('membership', $this->data);
        }
        $roles = $this->Membership->Role->find('list');
        $titles=$this->Membership->User->Title->find('list');
        $schemes=$this->Membership->User->Scheme->find('list');
        $protocols=$this->Membership->User->Protocol->find('list',array('order'=>'Protocol.rank Asc'));
        $this->set(compact('users','roles','titles','schemes','protocols'));
    }

    /**
     * Describe delete
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function delete($committee,$id = null) {
        $dcommittee=$this->Membership->Committee->findByShortName($committee);
        $this->set('dcommittee',$dcommittee);
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for Membership', true));
            $this->redirect(array('committee'=>$committee,'action'=>'index'));
        }
        $this->Membership->delete($id);
        $this->Session->setFlash(__('Membership deleted', true));
        $this->redirect(array('committee'=>$committee,'action'=>'index'));
    }
    function getemail() {
        Configure::write('debug', 0); // dont want debug in ajax returned html
        if ($this->RequestHandler->isAjax()) {
            $this->Membership->User->recursive=-1;
            $users=$this->Membership->User->find('all',array('conditions'=>array('User.email LIKE '=> '%'.$this->data['User']['email'].'%'),'fields'=>array('User.email')));
            $this->set('users',$users);
            $this->render('getemail','ajax');
        }
    } 
    
    function getusername() {
        Configure::write('debug', 0); // dont want debug in ajax returned html
        if ($this->RequestHandler->isAjax()) {
            $this->Membership->User->recursive=-1;
            $users=$this->Membership->User->find('all',array('conditions'=>array('User.username LIKE'=> $this->data['User']['username'].'%'),'fields'=>array('User.username')));
            $this->set('users',$users);
            $this->render('getusername','ajax');
        }
    } 

    function getname() {
        Configure::write('debug', 0); // dont want debug in ajax returned html
        if ($this->RequestHandler->isAjax()) {
            $this->Membership->User->recursive=-1;
            $users=$this->Membership->User->find('all',array('conditions'=>array('User.name LIKE '=> '%'.$this->data['User']['name'].'%'),'fields'=>array('User.name')));
            $this->set('users',$users);
            $this->render('getname','ajax');
        }
    } 
    
    function moveup($new_id=NULL, $new_committee_id=NULL){
        $id = $this->params['pass'][2];
        $committee_id = $this->params['pass'][1];
        $this->Membership->MovingUp($id,$committee_id);
        $comm['Committee']['id']=$committee_id;
        $comm['Committee']['membership_sorted']=1;
        $this->Membership->Committee->save($comm);
        $this->redirect(array('committee'=>$this->params['committee'],'action'=>'index'));
    }

    function movedown(){
        $id = $this->params['pass'][2];
        $committee_id = $this->params['pass'][1];
        $this->Membership->MovingDown($id,$committee_id);
        $comm['Committee']['id']=$committee_id;
        $comm['Committee']['membership_sorted']=1;
        $this->Membership->Committee->save($comm);
        $this->redirect(array('committee'=>$this->params['committee'],'action'=>'index'));
    }
    
}
?>
